package com.gs.m_goods_detail

import android.content.Context
import android.util.Log
import com.gs.common.API
import com.gs.common.callback.HttpCallback
import com.gs.common.callback.impl.CommonHttpCallback
import com.gs.common.constant.HttpCode
import com.gs.common.constant.StateCode
import com.gs.common.global.GlobalVariables
import com.gs.common.data.User
import okhttp3.Call
import okhttp3.Response
import org.json.JSONObject
import java.net.ConnectException
import java.net.SocketTimeoutException

class GoodsDetailModel(context: Context) {

    private val api by lazy { API.getInstance() }

    fun getUserInfoByUserId(userId: Int, block: (Int) -> Unit) {
        block.invoke(StateCode.STATE_LOADING)
        api.getUserInfoByUserId(userId, object : HttpCallback{
            override fun onSuccess(call: Call, result: String, response: Response) {
                val cookies = response.header("Set-Cookie")
                Log.d("cookies", "$cookies")
                val resultJSON = JSONObject(result)
                Log.d("result", result)
                Log.d("code", "${resultJSON["code"]}")
                if (resultJSON["code"] == HttpCode.SUCCESS_CODE) {
                    val phoneNumber = resultJSON["phoneNumber"].toString()
                    val username = resultJSON["username"].toString()
                    val address = resultJSON["address"].toString()
                    GlobalVariables.businessInfo = User(phoneNumber = phoneNumber, userName = username, token = "" ,address = address)
                    block.invoke(StateCode.STATE_SUCCESS)
                    return
                }
                block.invoke(StateCode.STATE_FAILED)
            }

            override fun onError(call: Call, e: Exception) {
                when(e) {
                    is ConnectException -> {
                        block.invoke(StateCode.NETWORK_ERROR)
                    }
                    is SocketTimeoutException -> {
                        block.invoke(StateCode.SERVER_ERROR)
                    }
                    else -> {
                        block.invoke(StateCode.UNKNOWN_ERROR)
                    }
                }
            }

        })
    }

    fun addGoodToCart(goodId: Int, username: String, block: (Int) -> Unit) {
        block.invoke(StateCode.STATE_LOADING)
        api.addGoodToCart(goodId, username, CommonHttpCallback(block))
    }

    fun getSoldCount(goodId: Int, block: (Int) -> Unit) {
        block.invoke(StateCode.STATE_LOADING)
        api.getSoldCountByGoodId(goodId, object : HttpCallback{
            override fun onSuccess(call: Call, result: String, response: Response) {
                val cookies = response.header("Set-Cookie")
                Log.d("cookies", "$cookies")
                val resultJSON = JSONObject(result)
                Log.d("result", result)
                Log.d("code", "${resultJSON["code"]}")
                if (resultJSON["code"] == HttpCode.SUCCESS_CODE) {
                    GlobalVariables.goodSoldCount = resultJSON["sold_count"].toString().toInt()
                    block.invoke(StateCode.STATE_SUCCESS)
                    return
                }
                block.invoke(StateCode.STATE_FAILED)
            }

            override fun onError(call: Call, e: Exception) {
                when(e) {
                    is ConnectException -> {
                        block.invoke(StateCode.NETWORK_ERROR)
                    }
                    is SocketTimeoutException -> {
                        block.invoke(StateCode.SERVER_ERROR)
                    }
                    else -> {
                        block.invoke(StateCode.UNKNOWN_ERROR)
                    }
                }
            }

        })
    }

    companion object{
        private var instance: GoodsDetailModel? = null
        fun getInstance(context: Context): GoodsDetailModel {
            if (instance == null) {
                synchronized(this::class) {
                    if (instance == null) {
                        instance = GoodsDetailModel(context)
                    }
                }
            }
            return instance!!
        }
    }
}